/*
* Copyright 2011 Pavel Kozhin 
*
* Licensed under the Apache License, Version 2.0 (the "License"); 
* you may not use this file except in compliance with the License. 
* You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software 
* distributed  under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
* See the License for the specific language governing permissions and 
* limitations under the License.
*
* Author: Pavel Kozhin.
*/
package org.etherframework.wire.metadata
{
	import flash.errors.IllegalOperationError;
	import flash.utils.Dictionary;
	
	import org.etherframework.common.wire.IWirable;
	import org.etherframework.core.reflection.MetadataInfo;
	import org.etherframework.core.utils.ClassType;
	import org.etherframework.core.utils.ClassUtils;

	public final class MetadataManager implements IMetadataManager
	{
		private static var _impl:MetadataManager;
		private var _initialized:Boolean = false;
		private var _tags:Vector.<String>; 
		private var _parser:MetadataParser;
		private const _metadataCache:Dictionary = new Dictionary();
		
		public static function getInstance():MetadataManager
		{
			if (!_impl)
				_impl = new MetadataManager();
			
			return _impl;
		}
		
		public function initialize(processors:Vector.<String>):void
		{
			if (_initialized)
				throw new IllegalOperationError("IMetadataManager is already initialized.");
			if (!processors)
				throw new ArgumentError("Argument processors:Vector.<String> can not be null.");
			
			_tags = processors.length ? processors : null;
			_parser = new MetadataParser(_tags);
			_initialized = true;
		}
		
		public function getMetadataInfo(classOrInstance:Object):MetadataInfo
		{
			ensureInitialized();
			
			if (!classOrInstance)
				throw new ArgumentError("Argument classOrInstance:Object can not be null.");
			
			var result:MetadataInfo;
			const type:ClassType = ClassUtils.describeClassType(classOrInstance);
			
			if (_metadataCache[type.name])
				return _metadataCache[type.name];
			
			result = _parser.getMetadataInfo(classOrInstance, 
				ClassUtils.implementsInterface(classOrInstance, IWirable)); 
			_metadataCache[type.name] = result;
			
			return  result;
		}
		
		public function clearCache():void
		{
			ensureInitialized();
			
			_parser = new MetadataParser(_tags);
			
			for (var item:String in _metadataCache)
				delete _metadataCache[item];
		}
		
		public function get initialized():Boolean { return _initialized; }
		
		private function ensureInitialized():void
		{
			if (!_initialized)
				throw new Error("MetadataManager should be initialized.");
		}
	}
}